<template>
    <el-container>
        <el-upload action="#" ref="cosupload" list-type="picture-card" accept=".jpg,.png" :auto-upload="true" :before-upload="beforeUpload" :http-request="upload">
            <template #>
                <i class="el-icon-plus" />
            </template>
            <template #file="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <el-progress type="circle" :visible="progressVisible" :percentage="percentage" :status="status" />
            </template>
        </el-upload>
    </el-container>
</template>
<script>
import COS from 'cos-js-sdk-v5';

export default {
    data() {
        return {
            progressVisible: false,
            percentage: 0,
            status: 'success'
        };
    },
    props: {
        clearFiles: {
            type: Boolean
        }
    },
    watch: {
        clearFiles(value) {
            if (value) this.$refs.cosupload.clearFiles();
        }
    },
    methods: {
        beforeUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            if (!(isJPG || isPNG)) {
                this.$message.error('上传图片只能是 JPG,PNG 格式!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        upload(file) {
            this.progressVisible = true;
            let that = this;
            let cos = new COS({
                SecretId: 'AKIDe6O9dpc41d47ycuxQcKsINFAqHBrDFfA',
                SecretKey: 'ziCQU4TdwhCuY4OfR2NYWEwEYbJpgHbh'
            });
            cos.putObject(
                {
                    Bucket: 'iya-1256891247',
                    Region: 'ap-guangzhou',
                    Key: new Date().getTime() + '-' + file.file.name,
                    StorageClass: 'STANDARD',
                    Body: file.file,
                    onProgress: function(progressData) {
                        const { speed, percent } = progressData;
                        if (speed === 0) {
                            that.status = 'exception';
                        }
                        that.percentage = percent * 100;
                        that.progressVisible = percent < 1;
                    }
                },
                function(err, data) {
                    if (err) {
                        console.log(err);
                    } else {
                        that.$emit('cosUploaded', 'https://' + data.Location);
                    }
                }
            );
        }
    }
};
</script>

<style scoped></style>
